package code.class1;

/**
 * https://leetcode.cn/problems/merge-strings-alternately/description/
 * 交替合并字符串
 */
public class Code15_MergeAlternately {
    public static void main(String[] args) {
        String str1 = "abc", str2 = "pqr";
        String res = mergeAlternately(str1, str2);
        System.out.println("res = " + res);
    }

    public static String mergeAlternately(String word1, String word2) {
        return process(word1.toCharArray(), word2.toCharArray());
    }

    public static String process(char[] arr1, char[] arr2) {
        // 返回字符串长度
        char[] ans = new char[arr1.length + arr2.length];
        // 数组下标
        int i = 0, j = 0, k = 0;
        // 遍历数组
        while (i < arr1.length && j < arr2.length) {
            // (k & 1) == 0 :表示 k%2,判断位数
            ans[k] = (k & 1) == 0 ? arr1[i++] : arr2[j++];
            k++;
        }
        // 追加未合并的字符
        while (i < arr1.length) {
            ans[k++] = arr1[i++];
        }
        while (j < arr2.length) {
            ans[k++] = arr2[j++];
        }
        return new String(ans);
    }
}
